package com.jack.leetcode.eachProblem07;

/**
 * Created by zhang_j on 2020/7/17
 */
public class 搜索插入位置 {

    public static void main(String[] args) {
        int[] a = {1,3,5,6};
        System.out.println(searchInsert(a, 5));
        System.out.println(searchInsert(a, 7));
        System.out.println(searchInsert(a, 0));
        System.out.println(searchInsert(a, 4));
    }

    public static int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while(left <= right){
            int mid = (left + right) / 2;
            if(target > nums[mid]){
                left = mid + 1;
            }else if(target < nums[mid]){
                right = mid - 1;
            }else{
                return mid;
            }
        }
        right = right < 0 ? 0 : right > nums.length-1 ? nums.length-1 : right;
        if(nums[right] <= target){
            return right + 1;
        }else{
            return right;
        }
    }
}
